import { Spin } from 'antd';
import { useEffect, useRef, useState } from 'react';

function Iframe({ src }: { src: string }) {
  const [spinning, setSpining] = useState(true);
  const contentRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    setSpining(true);
    const IframeDom = contentRef.current?.getElementsByTagName('iframe')[0] ?? document.createElement('iframe');
    IframeDom.style.display = 'none';
    IframeDom.style.width = '100%';
    IframeDom.style.height = '100%';
    IframeDom.style.border = 'none';

    IframeDom.onload = function () {
      IframeDom.style.display = '';
      setSpining(false);
    };
    IframeDom.onerror = function () {
      IframeDom.style.display = '';
      setSpining(false);
    };

    IframeDom.src = src;
    contentRef.current?.appendChild(IframeDom);
  }, [src]);

  return (
    <div style={{ height: '100%', width: '100%' }} ref={contentRef} className="iframe-content flex-center">
      {spinning ? <Spin size="large" spinning={true}></Spin> : null}
    </div>
  );
}

export { Iframe };
